import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useNotificationStore = defineStore('notification', () => {
  // ========== 状态管理 ==========
  
  // 通知开关状态（是否启用通知）
  const enabled = ref(false)
  
  // 通知列表
  const notifications = ref([
    {
      id: 1,
      type: 'system', // system, message, alert
      title: '系统更新',
      content: '检测到新版本 v2.0.1，建议及时更新',
      time: new Date(Date.now() - 3600000).toISOString(), // 1小时前
      read: false
    },
    {
      id: 2,
      type: 'message',
      title: '新消息',
      content: '您有一条新的系统消息待查看',
      time: new Date(Date.now() - 7200000).toISOString(), // 2小时前
      read: false
    },
    {
      id: 3,
      type: 'alert',
      title: '重要提醒',
      content: '您的账户安全设置需要更新，请尽快完成二次验证',
      time: new Date(Date.now() - 86400000).toISOString(), // 1天前
      read: true
    },
    {
      id: 4,
      type: 'system',
      title: '维护通知',
      content: '系统将于今晚22:00进行例行维护，预计持续1小时',
      time: new Date(Date.now() - 172800000).toISOString(), // 2天前
      read: true
    }
  ])
  
  // ========== 计算属性 ==========
  
  // 未读通知数量
  const unreadCount = computed(() => {
    if (!enabled.value) return 0 // 关闭状态不显示未读数
    return notifications.value.filter(n => !n.read).length
  })
  
  // 是否有未读通知
  const hasUnread = computed(() => unreadCount.value > 0)
  
  // 按时间分组的通知
  const groupedNotifications = computed(() => {
    const now = Date.now()
    const oneDay = 24 * 60 * 60 * 1000
    const twoDays = 2 * oneDay
    
    const groups = {
      today: [],
      yesterday: [],
      earlier: []
    }
    
    notifications.value.forEach(notif => {
      const notifTime = new Date(notif.time).getTime()
      const diff = now - notifTime
      
      if (diff < oneDay) {
        groups.today.push(notif)
      } else if (diff < twoDays) {
        groups.yesterday.push(notif)
      } else {
        groups.earlier.push(notif)
      }
    })
    
    return groups
  })
  
  // ========== 方法 ==========
  
  // 设置通知开关状态
  const setEnabled = (value) => {
    enabled.value = value
    // 保存到 localStorage
    localStorage.setItem('notificationEnabled', value ? '1' : '0')
  }
  
  // 初始化通知开关状态（从 localStorage 读取）
  const initEnabled = () => {
    const stored = localStorage.getItem('notificationEnabled')
    enabled.value = stored === '1'
  }
  
  // 标记单条通知为已读
  const markAsRead = (id) => {
    const notif = notifications.value.find(n => n.id === id)
    if (notif) {
      notif.read = true
    }
  }
  
  // 标记所有通知为已读
  const markAllAsRead = () => {
    notifications.value.forEach(n => {
      n.read = true
    })
  }
  
  // 删除单条通知
  const deleteNotification = (id) => {
    const index = notifications.value.findIndex(n => n.id === id)
    if (index !== -1) {
      notifications.value.splice(index, 1)
    }
  }
  
  // 清空所有通知
  const clearAll = () => {
    notifications.value = []
  }
  
  // 添加新通知（模拟推送）
  const addNotification = (notification) => {
    const newNotif = {
      id: Date.now(),
      type: notification.type || 'system',
      title: notification.title,
      content: notification.content,
      time: new Date().toISOString(),
      read: false
    }
    notifications.value.unshift(newNotif)
  }
  
  // 格式化时间显示
  const formatTime = (timeStr) => {
    const now = Date.now()
    const time = new Date(timeStr).getTime()
    const diff = now - time
    
    const minute = 60 * 1000
    const hour = 60 * minute
    const day = 24 * hour
    
    if (diff < minute) {
      return '刚刚'
    } else if (diff < hour) {
      return `${Math.floor(diff / minute)}分钟前`
    } else if (diff < day) {
      return `${Math.floor(diff / hour)}小时前`
    } else if (diff < 2 * day) {
      return '昨天'
    } else {
      const date = new Date(timeStr)
      return `${date.getMonth() + 1}-${date.getDate()}`
    }
  }
  
  // 获取通知类型图标
  const getTypeIcon = (type) => {
    const iconMap = {
      system: 'Bell',
      message: 'ChatDotRound',
      alert: 'Warning'
    }
    return iconMap[type] || 'Bell'
  }
  
  // 获取通知类型颜色
  const getTypeColor = (type) => {
    const colorMap = {
      system: '#409EFF',
      message: '#67C23A',
      alert: '#F56C6C'
    }
    return colorMap[type] || '#909399'
  }
  
  return {
    // 状态
    enabled,
    notifications,
    unreadCount,
    hasUnread,
    groupedNotifications,
    
    // 方法
    setEnabled,
    initEnabled,
    markAsRead,
    markAllAsRead,
    deleteNotification,
    clearAll,
    addNotification,
    formatTime,
    getTypeIcon,
    getTypeColor
  }
})

